package com.hc.hc_bot_kit

import android.content.Context
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/** HcBotKitPlugin */
class HcBotKitPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private lateinit var context: Context

    private val TAG = "HcBotKitPlugin"

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "hc_bot_kit")
        channel.setMethodCallHandler(this)

        context = flutterPluginBinding.applicationContext
        listenGuide()
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        try {
            val method = RobotMethod.valueOf(call.method)
            method.invoke(call, result, context)
        } catch (e: Exception) {
            Log.e(TAG, "onMethodCall: ${e.toString()}", )
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    private fun listenGuide() {
        RobotMethod.rosMain.setOnNavigationListener(
            object : NavigationLisenter {
                override fun stateChange(state: NavigationState) {
                    GlobalScope.launch(Dispatchers.Main) {
                        Log.e(TAG, "stateChange: ${state}", )
                        channel.invokeMethod("onNavStateChanged", state.toString())
                    }
                }
            }
        )
    }
}
